module app.controller.admin.LoginController;

import std.json;

import hunt.framework;
import app.model.User;
import app.repository.UserRepository;

import app.response.ResultMsg2;
import app.utils.RespCodeEnun;

/**
* 登录控制器
*/
class LoginController : Controller
{
    mixin MakeController;

    /**
    * 登录方法
    */
    @Action Response login()
    {
        UserRepository userRepository = new UserRepository();
        ResultMsg2 resultMsg = new ResultMsg2();

        string username = request.get("username", "");
        string password = request.get("password", "");

        if (username == "" || password == "")
        {
            this.response.setStatus(400);
            resultMsg.code = RespCodeEnun.Bad_Request;
            resultMsg.msg = "请输入用户名和密码";
        }

        try
        {
            User user = userRepository.findByUsernameAndPwd(username, password);
            if (user is null)
            {
                resultMsg.code = RespCodeEnun.Forbidden;
                resultMsg.msg = "用户名或密码错误";
            }
            else
            {
                import std.json : JSONValue;
                import std.datetime.systime : Clock;
                import core.time : hours;
                import hunt.jwt : JwtAlgorithm, JwtToken;

                JSONValue userJson = [
                    "id" : JSONValue(user.id),
                    "username" : JSONValue(user.username)
                ];
                // 生成token对象
                JwtToken token = new JwtToken(JwtAlgorithm.HS256);
                // 设置过期时间（2小时）
                token.claims.exp = (Clock.currTime() + 2.hours).toUnixTime();
                // 设置令牌
                token.claims.set("user", userJson);

                import app.utils.Const;

                // 生成token字符串
                string encodedToken = token.encode(Const.secret);

                resultMsg.code = RespCodeEnun.SUCCESS;
                resultMsg.msg = "success";
                resultMsg.token = encodedToken;
            }
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            resultMsg.code = RespCodeEnun.ERROR;
            resultMsg.msg = "系统异常";
        }

        return new JsonResponse(resultMsg);
    }
}
